package tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-11-23
 * Time：23:45
 */
public class EchoServer {
    ServerSocket socket = null;
    public EchoServer(int port) throws IOException {
        socket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务端已开启");
        ExecutorService ThreadPool = Executors.newCachedThreadPool();
        //建立连接
        while (true) {
            Socket clientSocket = socket.accept();
            // 处理接收
            //connectProcess (clientSocket);
            //1、使用多线程来连接多个客户端
            /*  Thread t = new Thread(() -> {
                connectProcess(clientSocket);
            });
            t.start();*/
            //2.放入线程池
            ThreadPool.submit(() -> {
                connectProcess(clientSocket);
            });

        }
    }

    public void connectProcess(Socket clientSocket) {
        System.out.printf("[%s:%d]已接入服务端\n", clientSocket.getInetAddress().toString(), clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            //使用Scanner和PrintWriter来读写，操作方便些
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true) {
                //1.检查客户端是否关闭，客户端关闭后，输入流才会读到EOF，从而返回false
                if (!scanner.hasNext()) {
                    System.out.printf("[%s:%d]与服务端断开连接\n", clientSocket.getInetAddress().toString(), clientSocket.getPort());
                    break;
                }
                //2.解析请求
                String request = scanner.next();
                //3.处理请求
                String response = process(request);
                //4.返回响应数据，这里不能用write，否则客户端会读不到换行
                printWriter.println(response);
                printWriter.flush();
                System.out.printf("[%s:%d] request：%s, response：%s\n",
                        clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(),
                        request, response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //这样处理可以避免发生异常导致文件未关闭
            try {
                clientSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        EchoServer echoServer = new EchoServer(8000);
        echoServer.start();
    }
}
